#include <iostream>
#include <thread>
#include <mutex>

using std::cout;
using std::endl;
using std::thread;
using std::mutex;

int gCnt = 0;
mutex mtx;//创建全局唯一的一把锁

//利用RAII的思想：利用栈对象的生命周期管理资源，当栈对象离开作用域的时候
//会自动执行析构函数
class MutexLockGuard
{
public:
    //在构造函数中上锁
    MutexLockGuard(mutex &mutx)
    : _mtx(mutx)
    {
        _mtx.lock();
    }

    MutexLockGuard(const MutexLockGuard &rhs) = delete;
    MutexLockGuard &operator=(const MutexLockGuard &rhs) = delete;

    //在析构函数中解锁
    ~MutexLockGuard()
    {
        _mtx.unlock();
    }
private:
    mutex &_mtx;
};

void threadFunc()
{
    for(size_t idx = 0; idx != 10000000; ++idx)
    {
        {
            MutexLockGuard autoLock(mtx);
            ++gCnt;
        }

        //...xxx
        //...yyy
    }
}

int main(int argc, char *argv[])
{
    thread th(threadFunc);
    thread th2(threadFunc);

    th.join();
    th2.join();

    cout << "gCnt = " << gCnt << endl;

    return 0;
}

